//package com.hundun.vision.biz.robot;
//
//import com.hundun.vision.biz.dto.KlineBarDTO;
//import com.hundun.vision.biz.dto.PositionDTO;
//import com.hundun.vision.biz.dto.SymbolDTO;
//import com.hundun.vision.biz.enums.OrderSide;
//import com.hundun.vision.biz.request.KlineRequest;
//import com.hundun.vision.biz.utils.KlineUtils;
//import com.hundun.vision.biz.utils.TimeUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Service;
//import org.ta4j.core.BarSeries;
//import org.ta4j.core.Rule;
//import org.ta4j.core.indicators.SMAIndicator;
//import org.ta4j.core.indicators.bollinger.BollingerBandsLowerIndicator;
//import org.ta4j.core.indicators.bollinger.BollingerBandsMiddleIndicator;
//import org.ta4j.core.indicators.bollinger.BollingerBandsUpperIndicator;
//import org.ta4j.core.indicators.helpers.ClosePriceIndicator;
//import org.ta4j.core.indicators.statistics.StandardDeviationIndicator;
//import org.ta4j.core.rules.OverIndicatorRule;
//import org.ta4j.core.rules.UnderIndicatorRule;
//
//import java.math.BigDecimal;
//import java.util.List;
//
//import static com.hundun.vision.biz.enums.OrderSide.BUY;
//import static com.hundun.vision.biz.enums.OrderSide.SELL;
//import static java.math.RoundingMode.DOWN;
//
///**
// * @author ：RuoChen
// * @date ：10:10 2024/11/30
// * @description：布林机器人
// */
//@Service
//@Slf4j
//public class BollingerRobotV2 extends Robot {
//    public void start() {
//        // 每次获取最新的市场价格并进行判断
//        while (true) {
//            try {
//                SymbolDTO pair = marketService.getSymbol(symbol);
//                if (pair == null) {
//                    log.info("get symbol error");
//                    continue;
//                }
//                Integer pricePrecision = pair.getPricePrecision();
//                KlineRequest request = new KlineRequest();
//                request.setSymbol(symbol);
//                request.setInterval(interval);
//                request.setLimit(limit);
//                request.setStartTime(TimeUtils.getStartTime(interval, limit));
//                request.setEndTime(System.currentTimeMillis());
//                List<KlineBarDTO> klineBars = marketService.getKlineBar(request);
//                BarSeries barSeries = KlineUtils.buildBarSeries(klineBars, interval);
//                int endIndex = barSeries.getEndIndex();
//                // 获取收盘价
//                ClosePriceIndicator closePrice = new ClosePriceIndicator(barSeries);
//                // 计算布林带
//                int bbPeriod = 20;
//                SMAIndicator sma = new SMAIndicator(closePrice, bbPeriod);
//                StandardDeviationIndicator stdDev = new StandardDeviationIndicator(closePrice, bbPeriod);
//                BollingerBandsMiddleIndicator middleBrand = new BollingerBandsMiddleIndicator(sma);
//                // 计算布林带上下轨
//                BollingerBandsUpperIndicator upperBand = new BollingerBandsUpperIndicator(middleBrand, stdDev);
//                BollingerBandsLowerIndicator lowerBand = new BollingerBandsLowerIndicator(middleBrand, stdDev);
//
//                // 计算布林带的上轨和下轨
//                BigDecimal upperBandValue = upperBand.getValue(endIndex).bigDecimalValue().setScale(pricePrecision, DOWN);
//                BigDecimal lowerBandValue = lowerBand.getValue(endIndex).bigDecimalValue().setScale(pricePrecision, DOWN);
//                // 布林带宽度
//                BigDecimal bandWidth = upperBandValue.subtract(lowerBandValue);
//
//                // 根据布林带上下轨计算买入和卖出价格
//                // 卖出价格
//                BigDecimal sellPrice = upperBandValue.add(bandWidth.multiply(priceStep)).setScale(pricePrecision, DOWN);
//                // 买入价格
//                BigDecimal buyPrice = lowerBandValue.subtract(bandWidth.multiply(priceStep)).setScale(pricePrecision, DOWN);
//
//                // 当前价格大于卖出价格：卖出（空单建仓）
//                Rule sellRule = new OverIndicatorRule(closePrice, sellPrice);
//                // 当前价格小于买入价格：买入（多单建仓）
//                Rule buyRule = new UnderIndicatorRule(closePrice, buyPrice);
//                // 当前价格小于布林带下线：买入（空单止盈）
//                Rule takeSellProfitRule = new UnderIndicatorRule(closePrice, lowerBand);
//                // 当前价格大于布林带上线：卖出（多单止盈）
//                Rule takeBuyProfitRule = new OverIndicatorRule(closePrice, upperBand);
//
//                BigDecimal price = barSeries.getBar(endIndex).getClosePrice().bigDecimalValue();
//                log.info("price:{}|upperBandPrice:{}|sellPrice:{}|interval:{}", price, upperBandValue, sellPrice,sellPrice.subtract(upperBandValue));
//                log.info("price:{}|lowerBandPrice:{}|buyPrice:{}|interval:{}", price, lowerBandValue, buyPrice,lowerBandValue.subtract(buyPrice));
//                OrderSide orderSide = null;
//                BigDecimal entryPrice = BigDecimal.ZERO;
//                BigDecimal position = BigDecimal.ZERO;
//                PositionDTO positionDTO = accountService.getPosition(symbol);
//                if (positionDTO != null) {
//                    orderSide = getOrderSide(positionDTO);
//                    entryPrice = positionDTO.getEntryPrice();
//                    position = positionDTO.getPositionAmt().abs();
//                    leverage = positionDTO.getLeverage();
//                }
//                // 入场
//                if (buyRule.isSatisfied(endIndex) && orderSide == null) {
//                    // 多单建仓
//                    log.info("start create buy order,price:{}|batchSize:{}|priceStep:{}", price, batchSize, priceStep);
//                    createOrder(true, BUY, false, price, null);
//                } else if (takeSellProfitRule.isSatisfied(endIndex) && SELL.equals(orderSide)) {
//                    // 空单止盈
//                    log.info("take sell profit,price:{}", price);
//                    createOrder(false, BUY, false, price, position);
//                } else if (isStopSatisfied(SELL, price, entryPrice) && SELL.equals(orderSide)) {
//                    // 空单止损
//                    log.info("stop sell loss,price:{}", price);
//                    createOrder(false, BUY, true, price, position);
//                }
//                // 出场
//                if (sellRule.isSatisfied(endIndex) && orderSide == null) {
//                    // 空单建仓
//                    log.info("start create sell order,price:{}|batchSize:{}|priceStep:{}", price, batchSize, priceStep);
//                    createOrder(true, SELL, false, price, null);
//                } else if (takeBuyProfitRule.isSatisfied(endIndex) && BUY.equals(orderSide)) {
//                    // 多单止盈
//                    log.info("take buy profit,price:{}", price);
//                    createOrder(false, SELL, false, price, position);
//                } else if (isStopSatisfied(BUY, price, entryPrice) && BUY.equals(orderSide)) {
//                    // 多单止损
//                    log.info("stop buy loss,price:{}", price);
//                    createOrder(false, SELL, true, price, position);
//                }
//                // 每10秒获取一次市场价格
//                Thread.sleep(5000);
//            } catch (InterruptedException e) {
//                log.error("Error occurred while sleep: {}", e.getMessage());
//            } catch (Exception e) {
//                log.error("Error occurred while loop: {}", e.getMessage());
//            }
//        }
//    }
//}